package com.learn.springboot.config.shiro;

import com.learn.springboot.domain.SysPermission;
import com.learn.springboot.domain.SysRole;
import com.learn.springboot.domain.User;
import com.learn.springboot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * @author dyz
 * @date 2020/6/13 17:25
 */
@Slf4j
public class EnchiladasShirlRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    /**
     * 执行授权逻辑 : 授权信息
     *
     * @param principalCollection 主要收集
     * @return {@link AuthorizationInfo}
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("doGetAuthorizationInfo ...");
        // 添加角色和权限
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 获取登录用户名
        String username = (String) principalCollection.getPrimaryPrincipal();

        User user = userService.findUserByName(username);

        for (SysRole role : user.getRoles()) {
            // 添加角色
            authorizationInfo.addRole(role.getRole());
            for (SysPermission permission : role.getPermissions()) {
                // 添加权限
                authorizationInfo.addStringPermission(permission.getName());
            }
        }
        return authorizationInfo;
    }

    /**
     * 执行认证逻辑 : 身份验证信息
     *
     * @param authenticationToken 身份验证令牌
     * @return {@link AuthenticationInfo}* @throws AuthenticationException 身份验证异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("doGetAuthenticationInfo ...");
        // 获取用户信息
        String username = (String) authenticationToken.getPrincipal();

        // 加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (username == null) {
            return null;
        }

        User user = userService.findUserByName(username);

        if (user == null) {
            //这里返回后会报出对应异常
            return null;
        }

        //这里验证authenticationToken和simpleAuthenticationInfo的信息
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()), getName());
        return authenticationInfo;
    }
}
